let i = 0;

function getUniqueString (prefix) {
  const randomKey = Math.random().toString(36).substr(2);
  return `${prefix ? prefix + '-' : ''}${randomKey}-${Date.now()}-${i++}`;
}

// 将16进制颜色转换成RGB格式
function hexToRgb (hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16),
    }
    : null;
}

/**
 * 转化为百分率
 */
function parseToPercentage (num, digit = 1) {
  if (num == null || num === 0) {
    return 0;
  }
  return (num * 100).toFixed(digit);
}

function parseMinReadable (mins) {
  if (mins == null || mins === 0) {
    return '0 \xa0min';
  }
  const hours = Math.floor(mins / 60);
  const remainMin = Math.round(mins % 60);
  return `${hours} \xa0h \xa0${remainMin} \xa0min`;
}

function withDefaultNumber (num, digit = 1) {
  if (num == null || num === 0) {
    return 0;
  }
  return num.toFixed(digit);
}

function timestampToTime(timestamp) {
  if (isEmpty(timestamp)) {
    return '';
  }
  if (timestamp === 0) {
    return '';
  }
  var date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
  return Y + M + D + h + m + s;
}

function timestampToDate(timestamp) {
  if (isEmpty(timestamp)) {
    return '';
  }
  if (timestamp === 0) {
    return '';
  }
  var date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return Y + M + D;
}

// 判断字符是否为空
function isEmpty(obj) {
  return (typeof obj === 'undefined' || obj === null || obj === "");
}

export default {
  getUniqueString,
  hexToRgb,
  parseToPercentage,
  parseMinReadable,
  withDefaultNumber,
  timestampToTime,
  timestampToDate,
  isEmpty,
};
